package com.le.tester.book.effectivejava3rdchinese.secondReading.l09;

import java.io.*;

/**
 * createTime：2024-08-14 9:35
 * description：使用try-with-resource代替try-finally
 */
public class TryClose {


    public static String firstLineOfFile(String path) throws Exception {

        //直接报警，建议使用try-with-resource
//        try {
//            return br.readLine();
//        } finally {
//            br.close();
//        }
        try (BufferedReader br = new BufferedReader(new FileReader(path))) {
            return br.readLine();
        }
    }

    //需要关闭两个io资源，实在难受
    public static void copy(String src, String dst) throws Exception {
//        InputStream in = new FileInputStream(src);
//
//        try {
//            OutputStream out = new FileOutputStream(dst);
//            try {
//                byte[] buf = new byte[1024];
//                int n;
//                while ((n = in.read(buf)) > 0) {
//                    out.write(buf, n, 0);
//                }
//            } finally {
//                out.close();
//            }
//        } finally {
//            in.close();
//        }

        try (InputStream in = new FileInputStream(src)) {
            try (OutputStream out = new FileOutputStream(dst)) {
                byte[] buf = new byte[1024];
                int n;
                while ((n = in.read(buf)) > 0) {
                    out.write(buf, n, 0);
                }
            }
        }

    }

    public static String firstLineOfLine(String path, String defaultVal) {
        try (BufferedReader br = new BufferedReader(new FileReader(path))) {
            return br.readLine();
        } catch (Exception e) {
            return defaultVal;
        }

    }
}
